import { useMutation, useQueryClient } from "@tanstack/react-query"
import toast from "react-hot-toast"

const useUpdateUserProfile = () => {
    const queryClient = useQueryClient()

    const { mutateAsync: upadteProfile, isPending: isUpdatingProfile } = useMutation({
        mutationFn: async (formData) => {
            try {
                const res = await fetch(`/api/users/update`, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify(formData),
                })

                const data = await res.json()
                if (!res.ok) {
                    throw new Error(data.error || "Something went wrong")
                }
                return data
            } catch (error) {
                throw new Error("Error in useUpdateUserProfile hook: " + error)
            }
        },

        OnSuccess: () => {
            toast.success("Profile updated successfully")
            Promise.all([
                queryClient.invalidateQuerise({
                    queryKey: ["authUser"]
                }),
                queryClient.invalidateQuerise({
                    queryKey: ["userProfile"]
                }),
            ])
        },

        OnError: (error) => {
            toast.error(error.message)
        },
    })

    return { upadteProfile, isUpdatingProfile }
}

export default useUpdateUserProfile